package nature.nano.environment;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Properties;

import nature.nano.component.Strings;

public class Config {

	private Properties props = new Properties();
	private Properties defaultValues = new Properties();   
	
	private boolean loadBasePropsSucceeded = false;
	private boolean loadDefaultValuesSucceeded = false;
	
	private String basePath;
	
	private static Config instance = new Config();
	
	public static Config current() {
		return instance;
	}

	private Config() {
		genBasePath();
		
		try {   
			InputStream inputStream = new FileInputStream(getPath(Strings.nanoStreamProperties));
			props.load(inputStream);
			inputStream.close();
			loadBasePropsSucceeded = true;
		} catch (Exception e) {
		}
		
		String defaultValuesFile = getPath(props.getProperty(Strings.defaultValuesFile));
		try {   
			InputStream inputStream = new FileInputStream(defaultValuesFile);
			defaultValues.load(inputStream);
			inputStream.close();
			loadDefaultValuesSucceeded = true;
		} catch (Exception e) {   
		}
	}

	private void genBasePath() {
		String nano = this.getClass().getProtectionDomain().getCodeSource().getLocation().toString();
		int i = nano.lastIndexOf("/");
		int j = nano.lastIndexOf("\\");
		int k = (i > j) ? i : j;
		if (nano.length() > 5) {
			basePath = nano.substring(5, k);
		} else {
			basePath = nano.substring(0, k);			
		}
	}
	
	public String getBasePath() {
		return basePath;
	}
	
	public String getPath(String path) {
		return basePath + "/" + path;
	}

	public String getProp(String key) {
		String value = props.getProperty(key);
		if (value == null) {
			return Strings.nil;
		}
		return value;
	}
	
	public String getDefaultValue(String key) {
		return defaultValues.getProperty(key);
	}
	
	public static void main(String[] args) {
		Config c = new Config();
		System.out.print(c.basePath);
	}

	public boolean isLoadBasePropsSucceeded() {
		return loadBasePropsSucceeded;
	}

	public boolean isLoadDefaultValuesSucceeded() {
		return loadDefaultValuesSucceeded;
	}
	
}
